package com.beta.resource.controllers;

import com.nimbusds.jose.shaded.json.JSONArray;
import com.nimbusds.jose.shaded.json.JSONObject;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;

@RestController
@RequestMapping("/testing")
public class RoleController {


    @GetMapping("/")
    public String home(JwtAuthenticationToken token) {
        Jwt credentials = (Jwt) token.getCredentials();
        return String.format("Welcome [%s] <br>"
                + "If you have the corresponding permissions,you can visit the following links<br><br>"
                + "<a href=\"auth/whoami\">Personal information</a><br><br>"
                + "<a href=\"vip\">Activity organization</a> (If you have [vip] rights)<br>"
                + "<a href=\"admin\">Product management</a>(If you have [admin] rights)<br><br>", credentials.getClaims().get("preferred_username"));
    }

    @GetMapping("auth/whoami")
    public String whoami(JwtAuthenticationToken token) {
        Jwt credentials = (Jwt) token.getCredentials();
        JSONObject value = (JSONObject) credentials.getClaims().get("realm_access");
        JSONArray roles = (JSONArray) value.get("roles");
        return String.format("%s Your email is: %s <br><br>" +
                "You have the following permissions:<br>%s<br><br>" +
                "Your Access Token is<br><br>%s", credentials.getClaims().get("name"), credentials.getClaims().get("email"), roles.toJSONString(), credentials.getTokenValue());
    }

    @GetMapping("vip")
    public String vip(){
        return "This is VIP page";
    }

    @GetMapping("admin")
    public String admin(){
        return "This is Admin page";
    }
}